<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国显科技演讲比赛实时投票</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/tableExport.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/FileSaver/FileSaver.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/js-xlsx/xlsx.full.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#6366F1',
                        dark: '#1E293B',
                        light: '#F8FAFC',
                        warning: '#F59E0B',
                        danger: '#EF4444'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-custom {
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
            .transition-custom {
                transition: all 0.3s ease;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <header class="bg-white shadow-md fixed w-full top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-tachometer text-primary text-2xl"></i>
                <h1 class="text-2xl font-bold text-dark">国显科技演讲比赛实时投票</h1>
            </div>
            <nav class="hidden md:flex space-x-6">
                <a href="/" class="text-dark font-medium hover:text-primary transition-colors">主界面</a>
                <a href="/admin" class="text-primary font-medium hover:text-primary/80 transition-colors">后台管理</a>
            </nav>
            <div class="md:hidden">
                <button id="menu-toggle" class="text-dark focus:outline-none">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="md:hidden hidden bg-white border-t border-gray-100">
            <div class="container mx-auto px-4 py-2 space-y-2">
                <a href="/" class="block py-2 text-dark font-medium">主界面</a>
                <a href="/admin" class="block py-2 text-primary font-medium">后台管理</a>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 pt-28 pb-16">
        <!-- 管理控制面板 -->
        <div class="bg-white rounded-xl shadow-custom p-6 mb-8 animate-fade-in">
            <h2 class="text-xl font-bold text-dark mb-6">控制面板</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <!-- 轮次选择 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">选择轮次</label>
                    <div class="flex flex-wrap gap-2">
                        <button class="round-btn px-4 py-2 rounded-lg bg-primary text-white font-medium" data-round="1">
                            第一轮
                        </button>
                        <button class="round-btn px-4 py-2 rounded-lg text-dark font-medium" data-round="2">
                            第二轮
                        </button>
                        <button class="round-btn px-4 py-2 rounded-lg text-dark font-medium" data-round="3">
                            第三轮
                        </button>
                        <button class="round-btn px-4 py-2 rounded-lg text-dark font-medium" data-round="4">
                            总决赛
                        </button>
                        <button class="round-btn px-4 py-2 rounded-lg text-dark font-medium" data-round="all">
                            全部轮次
                        </button>
                    </div>
                </div>
                
                <!-- 数据刷新 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">数据操作</label>
                    <div class="flex flex-wrap gap-2">
                        <button id="refresh-btn" class="px-4 py-2 bg-blue-100 text-primary rounded-lg font-medium flex items-center">
                            <i class="fa fa-refresh mr-2"></i> 刷新数据
                        </button>
                        <button id="export-btn" class="px-4 py-2 bg-green-100 text-green-600 rounded-lg font-medium flex items-center">
                            <i class="fa fa-download mr-2"></i> 导出数据
                        </button>
                    </div>
                </div>
                
                <!-- 视图切换 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">视图切换</label>
                    <div class="flex flex-wrap gap-2">
                        <button class="view-btn px-4 py-2 bg-primary text-white rounded-lg font-medium" data-view="chart">
                            <i class="fa fa-bar-chart mr-2"></i> 图表视图
                        </button>
                        <button class="view-btn px-4 py-2 text-dark rounded-lg font-medium" data-view="table">
                            <i class="fa fa-table mr-2"></i> 表格视图
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 筛选器 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- 分数范围筛选 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">票数范围</label>
                    <div class="flex items-center space-x-2">
                        <input type="number" id="min-score" min="0" max="100" placeholder="最低票数" 
                            class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <span class="text-gray-500">-</span>
                        <input type="number" id="max-score" min="0" max="100" placeholder="最高票数" 
                            class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>
                
                <!-- 选手搜索 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">搜索选手</label>
                    <div class="relative">
                        <input type="text" id="search-contestant" placeholder="输入选手姓名" 
                            class="w-full px-3 py-2 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <!-- 应用筛选 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700 invisible">操作</label>
                    <div class="flex space-x-2">
                        <button id="apply-filter" class="flex-1 px-4 py-2 bg-primary text-white rounded-lg font-medium">
                            应用筛选
                        </button>
                        <button id="reset-filter" class="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium">
                            重置
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据更新状态 -->
        <div class="flex justify-between items-center mb-6">
            <div id="update-status" class="flex items-center text-sm text-gray-500">
                <span id="last-update" class="mr-2">最后更新: 加载中...</span>
                <div class="relative inline-flex">
                    <div class="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
                </div>
            </div>
            <div id="data-stats" class="text-sm text-gray-500">
                共 <span class="font-semibold text-primary">0</span> 名选手
            </div>
        </div>

        <!-- 图表视图 -->
        <div id="chart-view" class="bg-white rounded-xl shadow-custom p-6 mb-8 transition-all duration-300 animate-fade-in">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-dark" id="chart-title">第一轮选手得分</h2>
                <div class="flex items-center space-x-4">
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="show-grid" class="rounded border-gray-300 text-primary focus:ring-primary/50" checked>
                        <label for="show-grid" class="text-sm text-gray-700">显示网格</label>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="sort-data" class="rounded border-gray-300 text-primary focus:ring-primary/50" checked>
                        <label for="sort-data" class="text-sm text-gray-700">排序数据</label>
                    </div>
                </div>
            </div>
            <div class="h-[500px]">
                <canvas id="adminChart"></canvas>
            </div>
        </div>

        <!-- 表格视图 (默认隐藏) -->
        <div id="table-view" class="bg-white rounded-xl shadow-custom p-6 mb-8 transition-all duration-300 hidden animate-fade-in">
            <h2 class="text-xl font-bold text-dark mb-6" id="table-title">第一轮选手得分</h2>
            <div class="overflow-x-auto">
                <table id="contestants-table" class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">选手姓名</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">票数</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">轮次</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <!-- 表格内容将通过JavaScript动态生成 -->
                        <tr>
                            <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                                <i class="fa fa-spinner fa-spin text-2xl mb-2 block"></i>
                                加载数据中...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 详细统计信息 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg animate-fade-in" style="animation-delay: 0.1s;">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">最高票数</h3>
                    <i class="fa fa-trophy text-amber-500 text-2xl"></i>
                </div>
                <div id="max-score-display" class="text-3xl font-bold text-primary">0票</div>
                <div id="max-score-name" class="text-sm text-gray-500 mt-1">-</div>
            </div>
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg animate-fade-in" style="animation-delay: 0.2s;">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">平均票数</h3>
                    <i class="fa fa-line-chart text-blue-500 text-2xl"></i>
                </div>
                <div id="avg-score-display" class="text-3xl font-bold text-blue-500">0票</div>
                <div class="text-sm text-gray-500 mt-1">所有显示选手的平均票数</div>
            </div>
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg animate-fade-in" style="animation-delay: 0.3s;">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">最低票数</h3>
                    <i class="fa fa-signal text-gray-500 text-2xl"></i>
                </div>
                <div id="min-score-display" class="text-3xl font-bold text-gray-600">0票</div>
                <div id="min-score-name" class="text-sm text-gray-500 mt-1">-</div>
            </div>
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg animate-fade-in" style="animation-delay: 0.4s;">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">标准差</h3>
                    <i class="fa fa-bar-chart text-purple-500 text-2xl"></i>
                </div>
                <div id="std-dev-display" class="text-3xl font-bold text-purple-500">0.0</div>
                <div class="text-sm text-gray-500 mt-1">票数分布的离散程度</div>
            </div>
        </div>

        <!-- 轮次对比图表 -->
        <div class="bg-white rounded-xl shadow-custom p-6 mb-8 transition-all duration-300 hover:shadow-lg animate-fade-in">
            <h2 class="text-xl font-bold text-dark mb-6">轮次票数对比</h2>
            <div class="h-[300px]">
                <canvas id="roundsComparisonChart"></canvas>
            </div>
        </div>
    </main>

    <!-- 模态框 -->
    <div id="modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-lg mx-4 transform transition-all animate-fade-in">
            <div class="p-6 border-b border-gray-200">
                <div class="flex justify-between items-center">
                    <h3 class="text-lg font-bold text-dark" id="modal-title">选手详情</h3>
                    <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
            </div>
            <div class="p-6" id="modal-content">
                <!-- 模态框内容将通过JavaScript动态生成 -->
            </div>
            <div class="p-4 border-t border-gray-200 flex justify-end space-x-3">
                <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg font-medium">关闭</button>
            </div>
        </div>
    </div>

    <script>
        // 移动端菜单切换
        document.getElementById('menu-toggle').addEventListener('click', function() {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });

        // 初始化变量
        let adminChart, roundsComparisonChart;
        let currentRound = '1';
        let currentView = 'chart';
        let lastUpdateTime = new Date();
        let allData = {};

        // 关闭模态框
        function closeModal() {
            document.getElementById('modal').classList.add('hidden');
        }

        // 打开模态框
        function openModal(title, content) {
            document.getElementById('modal-title').textContent = title;
            document.getElementById('modal-content').innerHTML = content;
            document.getElementById('modal').classList.remove('hidden');
        }

        // 模态框事件监听
        document.getElementById('close-modal').addEventListener('click', closeModal);
        document.getElementById('modal-cancel').addEventListener('click', closeModal);
        document.getElementById('modal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });

        // 计算标准差
        function calculateStandardDeviation(numbers) {
            const avg = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
            const squareDiffs = numbers.map(value => {
                const diff = value - avg;
                return diff * diff;
            });
            const avgSquareDiff = squareDiffs.reduce((sum, num) => sum + num, 0) / squareDiffs.length;
            return Math.sqrt(avgSquareDiff);
        }

        // 初始化管理图表
        function initAdminChart(labels, data, backgroundColor) {
            const ctx = document.getElementById('adminChart').getContext('2d');
            
            // 如果图表已存在，销毁它
            if (adminChart) {
                adminChart.destroy();
            }
            
            adminChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '票数',
                        data: data,
                        backgroundColor: backgroundColor || '#3B82F6',
                        borderColor: '#2563EB',
                        borderWidth: 1,
                        borderRadius: 4,
                        animation: {
                            duration: 1000,
                            easing: 'easeOutQuart'
                        }
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(30, 41, 59, 0.9)',
                            titleColor: '#F8FAFC',
                            bodyColor: '#CBD5E1',
                            borderColor: '#3B82F6',
                            borderWidth: 1,
                            padding: 12,
                            cornerRadius: 8,
                            callbacks: {
                                label: function(context) {
                                    return `票数: ${context.raw}票`;
                                }
                            }
                        },
                        // 显示柱状图上方的票数标签
                        datalabels: {
                            display: true,
                            color: '#1E293B',
                            font: {
                                weight: 'bold',
                                size: 12
                            },
                            formatter: function(value) {
                                return value + '票';
                            },
                            anchor: 'end',
                            align: 'top'
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: document.getElementById('show-grid').checked
                            },
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    size: 12
                                },
                                color: '#64748B',
                                maxRotation: 45,
                                minRotation: 0
                            }
                        },
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: {
                                display: document.getElementById('show-grid').checked,
                                color: 'rgba(226, 232, 240, 0.5)'
                            },
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    size: 12
                                },
                                color: '#64748B',
                                callback: function(value) {
                                    return value + '票';
                                }
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    }
                }
            });
        }

        // 初始化轮次对比图表
        function initRoundsComparisonChart() {
            const ctx = document.getElementById('roundsComparisonChart').getContext('2d');
            
            if (roundsComparisonChart) {
                roundsComparisonChart.destroy();
            }
            
            // 准备对比数据
            const rounds = ['1', '2', '3', '4'];
            const avgScores = [];
            const maxScores = [];
            const minScores = [];
            
            rounds.forEach(round => {
                if (allData && allData[round]) {
                    const scores = Object.values(allData[round]);
                    const avg = scores.reduce((sum, score) => sum + score, 0) / scores.length;
                    const max = Math.max(...scores);
                    const min = Math.min(...scores);
                    
                    avgScores.push(avg);
                    maxScores.push(max);
                    minScores.push(min);
                } else {
                    avgScores.push(0);
                    maxScores.push(0);
                    minScores.push(0);
                }
            });
            
            roundsComparisonChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: ['第一轮', '第二轮', '第三轮', '总决赛'],
                    datasets: [
                            {
                                label: '平均票数',
                                data: avgScores,
                                borderColor: '#3B82F6',
                                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                                tension: 0.3,
                                fill: true
                            },
                            {
                                label: '最高票数',
                                data: maxScores,
                                borderColor: '#10B981',
                                backgroundColor: 'transparent',
                                tension: 0.3,
                                borderDash: [5, 5]
                            },
                            {
                                label: '最低票数',
                                data: minScores,
                                borderColor: '#EF4444',
                                backgroundColor: 'transparent',
                                tension: 0.3,
                                borderDash: [5, 5]
                            }
                        ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 12,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': ' + context.raw + '票';
                                }
                            }
                        },
                        // 显示图表上的数据标签
                        datalabels: {
                            display: true,
                            color: '#1E293B',
                            font: {
                                weight: 'bold',
                                size: 10
                            },
                            formatter: function(value) {
                                return value + '票';
                            },
                            anchor: 'end',
                            align: 'top'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                callback: function(value) {
                                    return value + '票';
                                }
                            }
                        }
                    }
                }
            });
        }

        // 更新表格视图
        function updateTableView(data, round) {
            const tableBody = document.querySelector('#contestants-table tbody');
            tableBody.innerHTML = '';
            
            if (data && Object.keys(data).length > 0) {
                // 排序数据
                const sortedData = Object.entries(data)
                    .sort((a, b) => b[1] - a[1])
                    .map((entry, index) => ({ 
                        rank: index + 1, 
                        name: entry[0], 
                        score: entry[1],
                        round: round === 'all' ? '所有轮次' : `第${round}轮`
                    }));
                
                // 填充表格
                sortedData.forEach(item => {
                    const row = document.createElement('tr');
                    row.className = 'hover:bg-gray-50 transition-colors';
                    
                    // 设置排名背景色
                    let rankBgClass = '';
                    if (item.rank === 1) rankBgClass = 'bg-amber-100 text-amber-800';
                    else if (item.rank === 2) rankBgClass = 'bg-gray-100 text-gray-800';
                    else if (item.rank === 3) rankBgClass = 'bg-amber-50 text-amber-700';
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="${rankBgClass} w-7 h-7 rounded-full flex items-center justify-center font-medium text-sm">
                                    ${item.rank}
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="font-medium text-gray-900">${item.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center space-x-2">
                                <div class="text-sm font-medium text-gray-900">${item.score}</div>\n                                <div class="text-sm text-gray-500">票</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            ${item.round}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button class="view-details text-primary hover:text-primary/80 transition-colors" 
                                data-name="${item.name}" data-score="${item.score}">
                                查看详情
                            </button>
                        </td>
                    `;
                    
                    tableBody.appendChild(row);
                });
                
                // 添加详情按钮事件监听
                document.querySelectorAll('.view-details').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const name = this.getAttribute('data-name');
                        const score = this.getAttribute('data-score');
                        
                        // 构建详情内容
                        let detailsContent = `
                            <div class="space-y-4">
                                <div class="text-center">
                                    <h4 class="text-xl font-bold text-gray-900">${name}</h4>
                                    <p class="text-4xl font-bold text-primary mt-2">${score}票</p>
                                </div>
                                <div class="pt-4 border-t border-gray-100">
                                    <h5 class="text-sm font-medium text-gray-500 uppercase tracking-wider mb-2">票数趋势</h5>
                                    <div class="h-[150px]">
                                        <canvas id="contestantTrendChart"></canvas>
                                    </div>
                                </div>
                                <div class="grid grid-cols-2 gap-4 pt-4 border-t border-gray-100">
                                    <div class="p-3 bg-gray-50 rounded-lg">
                                        <p class="text-sm text-gray-500">排名</p>
                                        <p class="text-xl font-bold text-gray-900">${
                                            Object.entries(data)
                                                .sort((a, b) => b[1] - a[1])
                                                .findIndex(entry => entry[0] === name) + 1
                                        }</p>
                                    </div>
                                    <div class="p-3 bg-gray-50 rounded-lg">
                                        <p class="text-sm text-gray-500">与平均分的差距</p>
                                        <p class="text-xl font-bold text-${
                                            (parseFloat(score) - (Object.values(data).reduce((a, b) => a + b, 0) / Object.values(data).length) > 0 ? 'green' : 'red')
                                        }-500">
                                            ${
                                                (parseFloat(score) - (Object.values(data).reduce((a, b) => a + b, 0) / Object.values(data).length)).toFixed(1)
                                            }
                                        </p>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        openModal(`${name} 的详细信息`, detailsContent);
                        
                        // 初始化选手趋势图表
                        setTimeout(() => {
                            const ctx = document.getElementById('contestantTrendChart').getContext('2d');
                            const trendData = [];
                            const trendLabels = [];
                            
                            // 收集该选手在所有轮次的得分
                            for (let i = 1; i <= 4; i++) {
                                if (allData && allData[i] && allData[i][name]) {
                                    trendLabels.push(`第${i}轮`);
                                    trendData.push(allData[i][name]);
                                }
                            }
                            
                            new Chart(ctx, {
                                type: 'line',
                                data: {
                                    labels: trendLabels,
                                    datasets: [{
                                        label: '票数',
                                        data: trendData,
                                        borderColor: '#3B82F6',
                                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                                        tension: 0.3,
                                        fill: true
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        legend: {
                                            display: false
                                        }
                                    },
                                    scales: {
                                        y: {
                                            beginAtZero: true,
                                            max: 100
                                        }
                                    }
                                }
                            });
                        }, 100);
                    });
                });
            } else {
                // 无数据状态
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                        <i class="fa fa-info-circle text-2xl mb-2 block"></i>
                        暂无数据
                    </td>
                `;
                tableBody.appendChild(row);
            }
        }

        // 更新统计信息
        function updateStats(data) {
            if (data && Object.keys(data).length > 0) {
                const scores = Object.values(data);
                const sortedScores = [...scores].sort((a, b) => b - a);
                const maxScore = sortedScores[0];
                const minScore = sortedScores[sortedScores.length - 1];
                const avgScore = scores.reduce((sum, score) => sum + score, 0) / scores.length;
                const stdDev = calculateStandardDeviation(scores);
                
                // 找到最高分和最低分的选手
                let maxScoreName = '';
                let minScoreName = '';
                
                for (const [name, score] of Object.entries(data)) {
                    if (score === maxScore) maxScoreName = name;
                    if (score === minScore) minScoreName = name;
                }
                
                // 更新统计卡片
                document.getElementById('max-score-display').textContent = `${maxScore}分`;
                document.getElementById('max-score-name').textContent = maxScoreName;
                document.getElementById('min-score-display').textContent = `${minScore}分`;
                document.getElementById('min-score-name').textContent = minScoreName;
                document.getElementById('avg-score-display').textContent = `${avgScore.toFixed(1)}分`;
                document.getElementById('std-dev-display').textContent = stdDev.toFixed(1);
                
                // 更新数据统计
                document.querySelector('#data-stats span').textContent = Object.keys(data).length;
            }
        }

        // 应用筛选器
        function applyFilters(data) {
            let filteredData = { ...data };
            
            // 分数范围筛选
            const minScore = parseInt(document.getElementById('min-score').value);
            const maxScore = parseInt(document.getElementById('max-score').value);
            
            if (!isNaN(minScore)) {
                filteredData = Object.fromEntries(
                    Object.entries(filteredData).filter(([_, score]) => score >= minScore)
                );
            }
            
            if (!isNaN(maxScore)) {
                filteredData = Object.fromEntries(
                    Object.entries(filteredData).filter(([_, score]) => score <= maxScore)
                );
            }
            
            // 选手搜索筛选
            const searchTerm = document.getElementById('search-contestant').value.toLowerCase().trim();
            if (searchTerm) {
                filteredData = Object.fromEntries(
                    Object.entries(filteredData).filter(([name, _]) => name.toLowerCase().includes(searchTerm))
                );
            }
            
            return filteredData;
        }

        // 更新数据展示
        function updateDataDisplay(data, round) {
            // 应用筛选
            const filteredData = applyFilters(data);
            
            // 更新标题
            const roundTitle = round === 'all' ? '所有轮次' : `第${round}轮`;
            document.getElementById('chart-title').textContent = `${roundTitle}选手票数`;
            document.getElementById('table-title').textContent = `${roundTitle}选手票数`;
            
            // 根据当前视图更新显示
            if (currentView === 'chart') {
                // 排序数据
                const sortedData = document.getElementById('sort-data').checked 
                    ? Object.entries(filteredData).sort((a, b) => b[1] - a[1])
                    : Object.entries(filteredData);
                
                const labels = sortedData.map(item => item[0]);
                const scores = sortedData.map(item => item[1]);
                
                // 为数据项生成渐变色
                const backgroundColor = scores.map(score => {
                    if (score >= 90) return 'rgba(16, 185, 129, 0.7)'; // 绿色
                    if (score >= 80) return 'rgba(59, 130, 246, 0.7)'; // 蓝色
                    if (score >= 70) return 'rgba(245, 158, 11, 0.7)'; // 黄色
                    return 'rgba(239, 68, 68, 0.7)'; // 红色
                });
                
                // 更新图表
                initAdminChart(labels, scores, backgroundColor);
            } else {
                // 更新表格
                updateTableView(filteredData, round);
            }
            
            // 更新统计信息
            updateStats(filteredData);
            
            // 更新最后更新时间
            lastUpdateTime = new Date();
            const timeString = lastUpdateTime.toLocaleTimeString('zh-CN');
            document.getElementById('last-update').textContent = `最后更新: ${timeString}`;
        }

        // 获取指定轮次的数据
        function fetchRoundData(round) {
            currentRound = round;
            
            // 更新按钮样式
            document.querySelectorAll('.round-btn').forEach(btn => {
                if (btn.dataset.round === round) {
                    btn.classList.add('bg-primary', 'text-white');
                    btn.classList.remove('text-dark');
                } else {
                    btn.classList.remove('bg-primary', 'text-white');
                    btn.classList.add('text-dark');
                }
            });
            
            // 显示加载状态
            if (currentView === 'chart') {
                document.getElementById('adminChart').parentElement.innerHTML = `
                    <div class="flex items-center justify-center h-full">
                        <div class="text-center">
                            <i class="fa fa-spinner fa-spin text-3xl text-primary mb-3"></i>
                            <p class="text-gray-500">加载数据中...</p>
                        </div>
                    </div>
                `;
            } else {
                const tableBody = document.querySelector('#contestants-table tbody');
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                            <i class="fa fa-spinner fa-spin text-2xl mb-2 block"></i>
                            加载数据中...
                        </td>
                    </tr>
                `;
            }
            
            // 获取所有数据用于轮次对比
            fetch('/api/voting_data')
                .then(response => response.json())
                .then(allDataResponse => {
                    allData = allDataResponse;
                    initRoundsComparisonChart();
                })
                .catch(error => {
                    console.error('获取所有数据失败:', error);
                });
            
            // 获取指定轮次的数据
            let apiEndpoint = '';
            if (round === 'all') {
                apiEndpoint = '/api/voting_data/all';
            } else {
                apiEndpoint = `/api/voting_data/${round}`;
            }
            
            fetch(apiEndpoint)
                .then(response => response.json())
                .then(data => {
                    // 确保图表容器存在后再初始化
                    if (currentView === 'chart') {
                        const chartContainer = document.querySelector('#chart-container');
                        if (!document.getElementById('adminChart')) {
                            chartContainer.innerHTML = '<canvas id="adminChart"></canvas>';
                        }
                    }
                    
                    updateDataDisplay(data, round);
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    
                    // 使用模拟数据
                    const mockData = {
                        '张三': 85,
                        '李四': 90,
                        '王五': 78,
                        '赵六': 92,
                        '钱七': 88,
                        '孙八': 80
                    };
                    
                    // 确保图表容器存在后再初始化
                    if (currentView === 'chart') {
                        const chartContainer = document.querySelector('#chart-container');
                        if (!document.getElementById('adminChart')) {
                            chartContainer.innerHTML = '<canvas id="adminChart"></canvas>';
                        }
                    }
                    
                    updateDataDisplay(mockData, round);
                });
        }

        // 切换视图
        function switchView(view) {
            currentView = view;
            
            // 更新按钮样式
            document.querySelectorAll('.view-btn').forEach(btn => {
                if (btn.dataset.view === view) {
                    btn.classList.add('bg-primary', 'text-white');
                    btn.classList.remove('text-dark');
                } else {
                    btn.classList.remove('bg-primary', 'text-white');
                    btn.classList.add('text-dark');
                }
            });
            
            // 显示/隐藏对应视图
            if (view === 'chart') {
                document.getElementById('chart-view').classList.remove('hidden');
                document.getElementById('table-view').classList.add('hidden');
            } else {
                document.getElementById('chart-view').classList.add('hidden');
                document.getElementById('table-view').classList.remove('hidden');
            }
            
            // 刷新当前视图数据
            fetchRoundData(currentRound);
        }

        // 导出数据
        function exportData() {
            const roundTitle = currentRound === 'all' ? '所有轮次' : `第${currentRound}轮`;
            const exportDate = new Date().toLocaleDateString('zh-CN').replace(/\//g, '-');
            const filename = `国显科技演讲比赛_${roundTitle}_票数数据_${exportDate}.xlsx`;
            
            // 创建表格数据
            const tableData = [];
            tableData.push(['排名', '选手姓名', '得分']);
            
            let currentData = {};
            if (currentRound === 'all') {
                // 获取所有选手数据
                fetch('/api/voting_data/all')
                    .then(response => response.json())
                    .then(data => {
                        const sortedData = Object.entries(data)
                            .sort((a, b) => b[1] - a[1])
                            .map((entry, index) => [index + 1, entry[0], entry[1]]);
                        
                        sortedData.forEach(row => tableData.push(row));
                        
                        // 创建工作簿和工作表
                        const ws = XLSX.utils.aoa_to_sheet(tableData);
                        const wb = XLSX.utils.book_new();
                        XLSX.utils.book_append_sheet(wb, ws, "票数数据");
                        
                        // 导出文件
                        XLSX.writeFile(wb, filename);
                    })
                    .catch(error => {
                        console.error('导出数据失败:', error);
                        alert('导出数据失败，请重试');
                    });
            } else {
                // 获取当前轮次数据
                fetch(`/api/voting_data/${currentRound}`)
                    .then(response => response.json())
                    .then(data => {
                        const sortedData = Object.entries(data)
                            .sort((a, b) => b[1] - a[1])
                            .map((entry, index) => [index + 1, entry[0], entry[1]]);
                        
                        sortedData.forEach(row => tableData.push(row));
                        
                        // 创建工作簿和工作表
                        const ws = XLSX.utils.aoa_to_sheet(tableData);
                        const wb = XLSX.utils.book_new();
                        XLSX.utils.book_append_sheet(wb, ws, "得分数据");
                        
                        // 导出文件
                        XLSX.writeFile(wb, filename);
                    })
                    .catch(error => {
                        console.error('导出数据失败:', error);
                        alert('导出数据失败，请重试');
                    });
            }
        }

        // 设置轮次按钮点击事件
        document.querySelectorAll('.round-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                fetchRoundData(this.dataset.round);
            });
        });

        // 设置视图按钮点击事件
        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                switchView(this.dataset.view);
            });
        });

        // 设置刷新按钮点击事件
        document.getElementById('refresh-btn').addEventListener('click', function() {
            fetchRoundData(currentRound);
        });

        // 设置导出按钮点击事件
        document.getElementById('export-btn').addEventListener('click', exportData);

        // 设置筛选按钮点击事件
        document.getElementById('apply-filter').addEventListener('click', function() {
            fetchRoundData(currentRound);
        });

        // 设置重置筛选按钮点击事件
        document.getElementById('reset-filter').addEventListener('click', function() {
            document.getElementById('min-score').value = '';
            document.getElementById('max-score').value = '';
            document.getElementById('search-contestant').value = '';
            fetchRoundData(currentRound);
        });

        // 设置图表选项变更事件
        document.getElementById('show-grid').addEventListener('change', function() {
            fetchRoundData(currentRound);
        });

        document.getElementById('sort-data').addEventListener('change', function() {
            fetchRoundData(currentRound);
        });

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            fetchRoundData('1');
            
            // 每6秒自动刷新数据
            setInterval(function() {
                fetchRoundData(currentRound);
            }, 6000);
        });
    </script>
</body>
</html>